#include <iostream>
#include <thread>
#include <cstring>
#include <mysql/mysql.h>

int main(){

    MYSQL mysql;
    mysql_init(&mysql);
    const char* host = "127.0.0.1";
    const char* user = "root";
    const char* pass = "123456";
    const char* db = "mysql";

    //连接超时
    int to = 3;
    int re = mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,&to);
    if(re != 0){
        std::cerr<<"mysql_options failed!"<<mysql_error(&mysql)<<std::endl;
    }

    //自动重连
    int reconnect = 3;
    mysql_options(&mysql,MYSQL_OPT_RECONNECT,&reconnect);

    //连接（阻塞的）
    if(!mysql_real_connect(&mysql,host,user,pass,db,3306,0,0)){
        std::cerr<<"mysql connect failed!"<<mysql_error(&mysql)<<std::endl;
    }else{
        std::cout<<"mysql connect "<<host<<" success!"<<std::endl;
    }

    //1.执行sql语句
    const char *sql = "select * from user";
    //mysql_real_query() sql语句中可以包含二进制数据
    //mysql_query() sql语句只能是字符串
    re = mysql_real_query(&mysql,sql,strlen(sql));

    //2.获取结果集
    MYSQL_RES* result = mysql_use_result(&mysql);//不实际读取
    //MYSQL_RES* result = mysql_store_result(&mysql);//读取所有数据，注意缓存大小，MYSQL_OPT_MAX_ALLOWED_PACKET默认64M
    if(!result){
        std::cerr<<"mysql_use_result failed!"<<mysql_error(&mysql)<<std::endl;
    }
    //3.遍历结果集
    MYSQL_ROW row;
    while(row =mysql_fetch_row(result)){
        auto lens = mysql_fetch_lengths(result);
        std::cout<<lens[0]<<""<<row[0]<<","<<row[1]<<std::endl;
    }
    mysql_free_result(result);

    //Commands out of sync; you can't run this command now;必须对上一次结果做清理
    // re = mysql_query(&mysql,sql);
    // if(re != 0 ){
    //     std::cerr<<"mysql_real_query failed! "<<sql<<" "<<mysql_error(&mysql)<<std::endl;
    // }else{
    //     std::cout<<"mysql_real_query success! "<<host<<" success!"<<std::endl;
    // }

    mysql_close(&mysql);
    mysql_library_end();
    return 0;
}